package com.kantboot.business.bp.service.impl;

import com.kantboot.business.bp.domain.dto.BusBpProblemSearchDTO;
import com.kantboot.business.bp.domain.entity.BusBpProblem;
import com.kantboot.business.bp.domain.entity.BusBpProblemAnswer;
import com.kantboot.business.bp.domain.entity.BusBpProblemCollection;
import com.kantboot.business.bp.repository.BusBpProblemAnswerRepository;
import com.kantboot.business.bp.repository.BusBpProblemCollectionRepository;
import com.kantboot.business.bp.repository.BusBpProblemRepository;
import com.kantboot.business.bp.service.IBusBpProblemService;
import com.kantboot.system.user.domain.dto.BalanceChangeDTO;
import com.kantboot.system.user.service.ISysUserBalanceService;
import com.kantboot.system.user.service.IUserSelfService;
import com.kantboot.util.common.exception.BaseException;
import com.kantboot.util.core.param.PageParam;
import com.kantboot.util.core.result.PageResult;
import jakarta.annotation.Resource;
import jakarta.transaction.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class BusBpProblemServiceImpl implements IBusBpProblemService {

    @Resource
    private IUserSelfService userSelfService;

    @Resource
    private BusBpProblemRepository repository;

    @Resource
    private BusBpProblemAnswerRepository problemAnswerRepository;

    @Resource
    private BusBpProblemCollectionRepository problemCollectionRepository;

    /**
     * 根据id查询
     */
    @Override
    public BusBpProblem getById(Long id) {
        BusBpProblem busBpProblem = repository.findById(id).get();
        // 查询问题的是否自己收藏
        List<BusBpProblemCollection> byUserIdAndProblemId = problemCollectionRepository
                .findByUserIdAndProblemId(userSelfService.getSelfId(), id);
        if (byUserIdAndProblemId.size() > 0) {
            busBpProblem.setIsCollectedSelf(true);
        }
        return busBpProblem;
    }

    /**
     * 发布问题
     * @param busBpProblem 实体
     * @return 实体
     */
    @Override
    public BusBpProblem push(BusBpProblem busBpProblem) {
        // 设置用户ID
        busBpProblem.setUserId(userSelfService.getSelfId());
        busBpProblem.setCollectionCount(0L);
        return repository.save(busBpProblem);
    }

    /**
     * 回答问题
     */
    @Override
    public BusBpProblemAnswer answer(BusBpProblemAnswer busBpProblemAnswer) {
        // 设置用户ID
        busBpProblemAnswer.setUserId(userSelfService.getSelfId());
        busBpProblemAnswer.setIsRecognized(false);
        return problemAnswerRepository.save(busBpProblemAnswer);
    }

    @Override
    public List<BusBpProblem> getSelfProblem() {
        List<BusBpProblem> byUserId = repository.findByUserId(userSelfService.getSelfId());
        for (BusBpProblem busBpProblem : byUserId) {
            // 查询问题的是否自己收藏
            List<BusBpProblemCollection> byUserIdAndProblemId = problemCollectionRepository
                    .findByUserIdAndProblemId(userSelfService.getSelfId(), busBpProblem.getId());
            if (byUserIdAndProblemId.size() > 0) {
                busBpProblem.setIsCollectedSelf(true);
            }
        }
        return byUserId;
    }

    @Override
    public List<BusBpProblem> getBodyDataFront(BusBpProblemSearchDTO dto) {

        Boolean flag = false;

        Long selfId = null;
        try {
            selfId = userSelfService.getSelfId();
        } catch (Exception e) {
            flag = true;
        }

        List<BusBpProblem> bodyDataFront = repository.getBodyDataFront(dto);
        if(!flag) {
            return bodyDataFront;
        }
        for (BusBpProblem busBpProblem : bodyDataFront) {
            // 如果有自己的问题，设置isCollectedSelf为true
            List<BusBpProblemCollection> byUserIdAndProblemId = problemCollectionRepository.findByUserIdAndProblemId(selfId, busBpProblem.getId());
            if (byUserIdAndProblemId.size() > 0) {
                busBpProblem.setIsCollectedSelf(true);
            }
        }

        return bodyDataFront;
    }

    /**
     * 收藏问题
     */
    @Transactional
    @Modifying
    @Override
    public void collect(Long problemId) {
        // 判断用户是否已经收藏过该问题
        List<BusBpProblemCollection> byUserIdAndProblemId = problemCollectionRepository.findByUserIdAndProblemId(userSelfService.getSelfId(), problemId);
        if (byUserIdAndProblemId.size() > 0) {
            throw BaseException.of("isAlreadyCollected", "已经收藏过该问题");
        }

        // 创建一个问题收藏实体
        BusBpProblemCollection collection = new BusBpProblemCollection();
        // 设置问题ID
        collection.setProblemId(problemId);
        // 设置用户ID
        collection.setUserId(userSelfService.getSelfId());
        // 保存问题收藏
        problemCollectionRepository.save(collection);

        // 获取问题现在的收藏数
        BusBpProblem problem = repository.findById(problemId).get();
        // 如果问题数为空，设置为1
        if (problem.getCollectionCount() == null) {
            problem.setCollectionCount(1L);
        } else {
            // 否则+1
            problem.setCollectionCount(problem.getCollectionCount() + 1);
        }
        // 保存问题
        repository.save(problem);
    }

    /**
     * 取消收藏问题
     */
    @Transactional
    @Modifying
    @Override
    public void cancelCollect(Long problemId) {
        // 删除问题收藏
        problemCollectionRepository.deleteByUserIdAndProblemId(userSelfService.getSelfId(), problemId);

        // 获取问题现在的收藏数
        BusBpProblem problem = repository.findById(problemId).get();
        // 如果问题数为空，设置为0
        if (problem.getCollectionCount() == null) {
            problem.setCollectionCount(0L);
        } else {
            // 否则-1
            problem.setCollectionCount(problem.getCollectionCount() - 1);
        }
        // 保存问题
        repository.save(problem);
    }

    @Override
    public List<BusBpProblemCollection> getSelfCollection() {
        Long selfId = userSelfService.getSelfId();
        List<BusBpProblemCollection> byUserId = problemCollectionRepository.findByUserId(userSelfService.getSelfId());
        for (BusBpProblemCollection busBpProblemCollection : byUserId) {
            // 查询问题的是否自己收藏
            List<BusBpProblemCollection> byUserIdAndProblemId = problemCollectionRepository
                    .findByUserIdAndProblemId(selfId, busBpProblemCollection.getProblemId());
            if (byUserIdAndProblemId.size() > 0) {
                busBpProblemCollection.setProblem(busBpProblemCollection.getProblem().setIsCollectedSelf(true));
            }
        }
        return byUserId;
    }

    @Resource
    private ISysUserBalanceService userBalanceService;

    @Override
    public void recognizedAnswer(Long answerId) {

        BusBpProblemAnswer answer = problemAnswerRepository.findById(answerId).get();
        answer.setIsRecognized(true);
        problemAnswerRepository.save(answer);

        BalanceChangeDTO dto = new BalanceChangeDTO();
        dto.setUserId(answer.getUserId());
        dto.setBalanceCode("integral");
        dto.setNumber(new BigDecimal(1));
        dto.setReasonCode("recognizedAnswer");
        userBalanceService.changeBalance(dto);


    }

    @Override
    public PageResult getBodyData(PageParam<BusBpProblemSearchDTO> pageParam) {
        Page<BusBpProblem> bodyData = repository.getBodyData(pageParam.getData(), pageParam.getPageable());
        return PageResult.of(bodyData);
    }
}
